<template>
  <div>
    <!-- action          上传图片的地址 默认上传行为 -->
    <!-- show-file-list  展示图片列表 -->
    <!-- on-success      上传成功后的钩子 -->
    <!-- before-upload   上传之前的钩子 -->
    <!-- 因为要上传至腾讯云 所以要用自定义上传行为http-request 同时需要将action设置为#-->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>
<script>
// 导入COS
const COS = require('cos-js-sdk-v5')
// 初始化
var cos = new COS({
  SecretId: 'AKIDYswkHWVDfV4MO9dpkPowoPjlW0DAqGOF',
  SecretKey: 'bw0nJYWDdmeFadQwB8oDLDo9D4f17UbR'
})
export default {
  name: 'UploadImage',
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    // 自定义上传行为 传入形参file 当前选择的图片信息
    upload(file) {
      // 显示进度条
      this.showProgress = true
      // console.log(file)
      if (file.file) {
        cos.putObject({
          Bucket: 'renzi-1307084507', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: file.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: file.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
          }
        }, (err, data) => {
          // console.log(err || data)
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.showProgress = false
          }
        })
      }
    },

    // 上传图片成功后 的处理
    handleAvatarSuccess(res, file) {
      // 将图片转换为地址
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    // 上传之前的处理函数(校验)
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
